import json
import sys
import time

import requests
from PyQt5 import QtCore
from PyQt5.QtWidgets import QMessageBox, QApplication, QDialog

import constant
import login
import main

def login(self, url=constant.API_HOST + '/login'):
    username = self.input_phone
    password = self.input_password
    if not username.text():
        QMessageBox.about(self, '提示', '请输入手机号码')
        username.setFocus()
    elif not password.text():
        QMessageBox.about(self, '提示', '请输入登录密码')
        password.setFocus()
    else:
        try:
            data = {
                # 'login_type': 'phone',
                'username': username.text(),
                'password': password.text()
            }
            response = requests.post(url, data)
            if response.status_code == 200:
                res = json.loads(response.text)
                if res['code'] == 0:
                    QMessageBox().about(self, '提示', '登录成功')
                    self.token = res['data']['token']
                    self.close()
                    mainwindow = main.MainWindow(self.token)
                    mainwindow.show()
                else:
                    QMessageBox().about(self, '提示', res['message'])
                    username.setFocus()
            else:
                QMessageBox().about(self, '提示', '服务器错误')

        except requests.exceptions.ConnectionError:
            QMessageBox().about(self, '提示', '服务器连接失败')

        except Exception as err:
            print("Main Unexpected error:", sys.exc_info())  # sys.exc_info()返回出错信息


def post(self, url, data):
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            constant.X_TOKEN: self.token
        }
        print(f"token: {self.token}")
        print("post url: " + url)
        print(data)
        response = requests.post(url, data=json.dumps(data), headers=headers)
        if response.status_code == 200:
            res = json.loads(response.text)
            print("post res: " + json.dumps(res))
            if res['code'] == constant.TOKEN_INVALID:
                print(self)
                self.close()
            elif res['code'] == constant.OK:
                return res
        else:
            QMessageBox().about(self, '提示', '服务器错误')

    except requests.exceptions.ConnectionError:
        QMessageBox().about(self, '提示', '服务器连接失败')

    except Exception as err:
        print("Main Unexpected error:", sys.exc_info())  # sys.exc_info()返回出错信息

def put(self, url, data):
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            constant.X_TOKEN: self.token
        }
        print(f"token: {self.token}")
        print("put url: " + url)
        print(data)
        response = requests.put(url, data=json.dumps(data), headers=headers)
        if response.status_code == 200:
            res = json.loads(response.text)
            print("put res: " + json.dumps(res))
            if res['code'] == constant.TOKEN_INVALID:
                print(self)
                self.close()
            elif res['code'] == constant.OK:
                return res
        else:
            QMessageBox().about(self, '提示', '服务器错误')

    except requests.exceptions.ConnectionError:
        QMessageBox().about(self, '提示', '服务器连接失败')

    except Exception as err:
        print("Main Unexpected error:", sys.exc_info())  # sys.exc_info()返回出错信息


def get(self, url, data=None):
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            constant.X_TOKEN: self.token
        }
        print(f"token: {self.token}")
        print("get url: " + url)
        print(data)
        response = requests.get(url, data=json.dumps(data), headers=headers)
        print(str(response.status_code) + " " + response.text)
        if response.status_code == 200:
            res = json.loads(response.text)
            print("get res: " + json.dumps(res))
            if res['code'] == constant.TOKEN_INVALID:
                result = QMessageBox.question(self, "恒通房管", "登录失效，请重新登录",
                                              QMessageBox.Yes)
                if result == QMessageBox.Yes:
                    QtCore.QTimer.singleShot(0, self.close)

            elif res['code'] == constant.OK:
                return res
        else:
            QMessageBox().about(self, '提示', '服务器错误')
    except requests.exceptions.ConnectionError:
        QMessageBox().about(self, '提示', '服务器连接失败')

    except Exception as err:
        print("Main Unexpected error:", sys.exc_info())  # sys.exc_info()返回出错信息
